<template>
  <EchartsUI ref="chartRef" style="height: 560px" />
</template>

<script setup>
import { watch, ref, nextTick } from 'vue';
import { EchartsUI, useEcharts } from '@vben/plugins/echarts';

const chartRef = ref(null);
const { renderEcharts } = useEcharts(chartRef);

const props = defineProps({
  usageSituationDataFilter: {
    type: Object,
    default: () => ({ orgName: [], orgData: [] })
  },
});

// 截断函数
const formatName = (name) => (name && name.length > 5 ? name.slice(0, 5) + '...' : name);

// option 响应式
const option = ref({
  backgroundColor: 'transparent',
  grid: {
    top: 30,
    bottom: 30,
    left: '3%',
    right: '4%',
    containLabel: true,
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line',
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.3)',
        width: 1,
        type: 'dashed',
      },
    },
  },
  legend: {
    data: [],
    textStyle: {
      color: '#fff',
      fontSize: 12,
    },
    top: 0,
    icon: 'roundRect',
    itemWidth: 12,
    itemHeight: 6,
    itemGap: 20,
    formatter: formatName,
  },
  xAxis: {
    nameTextStyle: {
      color: '#fff',
      padding: [5, 0, 0, 0],
    },
    data: [],
    axisLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.5)',
      },
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12,
      interval: 0, // 展示全部x轴
      margin: 8,
      formatter: formatName,
    },
  },
  yAxis: {
    nameTextStyle: {
      color: '#fff',
      padding: [0, 0, 5, 0],
    },
    axisLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.5)',
      },
    },
    axisLabel: {
      color: '#fff',
      fontSize: 12,
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(255, 255, 255, 0.1)',
      },
    },
  },
  series: [],
});

// 监听数据变化，动态更新 option
watch(
  () => props.usageSituationDataFilter,
  (newVal) => {
    if (
      !newVal ||
      !Array.isArray(newVal.orgName) ||
      !Array.isArray(newVal.orgData) ||
      newVal.orgName.length === 0
    ) {
      option.value.legend.data = [];
      option.value.xAxis.data = [];
      option.value.series = [];
      renderEcharts(option.value);
      return;
    }
    // 先清空
    option.value.series = [];
    renderEcharts(option.value);
    // 再渲染新数据
    nextTick(() => {
      option.value.legend.data = newVal.orgName;
      option.value.xAxis.data = newVal.orgName;
      option.value.series = [
        {
          name: '数量',
          type: 'line',
          data: newVal.orgData,
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          lineStyle: {
            width: 3,
            color: '#00eaff',
          },
          itemStyle: {
            color: '#00eaff',
          },
          animation: true,
          animationDuration: 300,
          animationEasing: 'cubicOut',
        }
      ];
      renderEcharts(option.value);
    });
  },
  { deep: true, immediate: true }
);
</script>
